﻿// MeetingMenuSpan
function clickMeetingRecordRow(trNode)
{
    var currentRow = trNode;
    if (!currentRow.classList.contains("SelectedMeetingRow")) {
        var trNodes = document.querySelectorAll(".MeetingRecordRow");
        for (var i = 0; i < trNodes.length; i++) {
            var trNode = trNodes[i];
            if (trNode != currentRow && trNode.classList.contains("SelectedMeetingRow")) {
                trNode.classList.remove("SelectedMeetingRow");
            }
        }

        currentRow.classList.add("SelectedMeetingRow");

        var meetingMenuSpan = currentRow.querySelector(".MeetingMenuSpan");
        if (meetingMenuSpan) {
            meetingMenuSpan.click();
        }
    }
}

function getCurrentSelectedRow() {
    var currentRow = document.querySelector(".SelectedMeetingRow");
    while (!currentRow) {
        currentRow = document.querySelector(".SelectedMeetingRow");
    }

    return currentRow;   
}

$(document).ready(function () {
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", RefreshMeetingRecordsData);

    // SearchIcon
    var searchIcon = document.getElementById("SearchIcon");
    searchIcon.onclick = SearchMeetingRecords;

    var allMeetingRecord = document.getElementById("AllMeetingRecord");
    allMeetingRecord.onclick = ShowAllMeetingRecord;

    $("#SearchInput").keyup(function (e) {
        if (e.keyCode == 13) {
            SearchMeetingRecords();
        }
    });
});

function ShowAllMeetingRecord()
{
    RefreshMeetingRecordsData();
}
String.prototype.Trim = function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

function SearchMeetingRecords()
{
    var searchInput = document.getElementById("SearchInput");
    var searchText = searchInput.value;
    if (searchText == null || searchText == "" || searchText.Trim() == "") {
        alert("请输入搜索字符串");
    }
    else {
        RefreshMeetingRecordsData(searchText.Trim());
    }
}

var meetingRecordItems;
function RefreshMeetingRecordsData(searchText) {
    // SearchInput
    if (!searchText) {
        var searchInput = document.getElementById("SearchInput");
        searchInput.value = "";
    }

    // MeetingRecordBusy
    var meetingRecordBusy = document.getElementById("MeetingRecordBusy");
    if (meetingRecordBusy.classList.contains("hidden")) {
        meetingRecordBusy.classList.remove("hidden");
    }

    // MeetingRecordTable
    var meetingRecordTable = document.getElementById("MeetingRecordTable");
    meetingRecordTable = meetingRecordTable.classList.add("hidden");
    ClearRowInTable("MeetingRecordTable");

    // 
    var clientContext = new SP.ClientContext();
    var web = clientContext.get_web();
    var recordList = web.get_lists().getByTitle(globalConfig.recordListName);
    var camlQuery = new SP.CamlQuery();

    var where = "";
    if (searchText) {
        where = "<Where><And><Contains>" +
                  "<FieldRef Name='MeetingSubject' />" +
                  "<Value Type='Text'>" + searchText.Trim() + "</Value>" +
                "</Contains>" +
                " <IsNotNull><FieldRef Name='MeetingSubject' /></IsNotNull>" +
                "</And></Where>";
    }
    else {
        where = "<Where>" +
                " <IsNotNull><FieldRef Name='MeetingSubject' /></IsNotNull>" +
                "</Where>";
    }

            camlQuery.set_viewXml("<View><Query>" + where + "<OrderBy><FieldRef Name='MeetingDate' Ascending='TRUE' /></OrderBy></Query><RowLimit>10000</RowLimit></View>");
    meetingRecordItems = recordList.getItems(camlQuery);
    clientContext.load(meetingRecordItems, 'Include(Id,MeetingSubject,MeetingDate,MeetingHoster,MeetingAttend,MeetingLength,LinkFilename,FileSizeDisplay)');
    clientContext.executeQueryAsync(successHandlerForQueryMeetingRecords, onFailureForQueryMeetingRecords);
}
var loadedTheVedio = false;
function successHandlerForQueryMeetingRecords() {
    var firstVedio = null;
    var meetingRecordEnumerator = meetingRecordItems.getEnumerator();
    var meetingRecords = new MeetingRecords();
    meetingRecords.meetingRecords = new Array();
    meetingRecords.totalRecords = 0;
    while (meetingRecordEnumerator.moveNext()) {
        var meetingRecordItem = meetingRecordEnumerator.get_current();
        meetingRecords.totalRecords++;
        var meetingRecord = new MeetingRecord();
        meetingRecord.meetingSubject = meetingRecordItem.get_item("MeetingSubject");
        meetingRecord.rowId = meetingRecordItem.get_id();
        meetingRecord.fileUrl = meetingRecordItem.get_item("LinkFilename");
        var meetingAttends = meetingRecordItem.get_item("MeetingAttend");
        var meeetingAttendStr = "";
        for (var index = 0; meetingAttends && index < meetingAttends.length; index++) {
            meetingAttend = meetingAttends[index];
            if (meeetingAttendStr != "") {
                meeetingAttendStr += "," + meetingAttend.get_lookupValue();
            }
            else {
                meeetingAttendStr += meetingAttend.get_lookupValue();
            }
        }

        meetingRecord.meetingAttend = meeetingAttendStr;
        meetingRecord.meetingHoster = meetingRecordItem.get_item("MeetingHoster").get_lookupValue();
        meetingRecord.meetingDate = meetingRecordItem.get_item("MeetingDate");
        meetingRecord.meetingFileSize = (meetingRecordItem.get_item("FileSizeDisplay") / (1024 * 1024.0)).toFixed(2) + "MB";
        meetingRecord.meetingLength = meetingRecordItem.get_item("MeetingLength") + "分钟";

        // (record.meetingDate.getMonth() + 1) + '/' + record.meetingDate.getDate() + '/' +  record.meetingDate.getFullYear()
        meetingRecord.meetingDate = meetingRecord.meetingDate.getFullYear() + "/" + (meetingRecord.meetingDate.getMonth() + 1) + "/" + meetingRecord.meetingDate.getDate();
        meetingRecords.meetingRecords.push(meetingRecord);

        if (!firstVedio) {
            firstVedio = globalConfig.meetRecordFolder + meetingRecord.fileUrl;            
        }

    }

    globalConfig.meetingRecords = meetingRecords;
    meetingRecords.currentPage = 1;
    meetingRecords.startIndex = 0;
    if (meetingRecords.totalRecords >= meetingRecords.recordPageSzie) {
        meetingRecords.endIndex = meetingRecords.recordPageSzie - 1;
    }
    else {
        meetingRecords.endIndex = meetingRecords.totalRecords -1;
    }

    RenderMeetingRecords();
    var meetingRecordBusy = document.getElementById("MeetingRecordBusy");
    var meetingRecordTable = document.getElementById("MeetingRecordTable");
    meetingRecordBusy.classList.add("hidden");
    meetingRecordTable.classList.remove("hidden");

    var meetingRecordPreviousPage = document.getElementById("MeetingRecordPreviousPage");
    meetingRecordPreviousPage.onclick = MeetingRecordPreviousPage;

    var meetingRecordNextPage = document.getElementById("MeetingRecordNextPage");
    meetingRecordNextPage.onclick = MeetingRecorNextPage;

    if (firstVedio && !loadedTheVedio) {
        loadedTheVedio = true;
        PlayerMediaBySliverlight(firstVedio);
    }
}

function RenderMeetingRecords() {
    var meetingRecordTable = document.getElementById("MeetingRecordTable");
    ClearRowInTable("MeetingRecordTable");
  

    var delta = globalConfig.meetingRecords.endIndex - globalConfig.meetingRecords.startIndex;
    if (delta > 15) {
        meetingRecordTable.style.width = "579px";
    }
    else {
        meetingRecordTable.style.width = "595px";
    }
    for (var index = globalConfig.meetingRecords.startIndex; index <= globalConfig.meetingRecords.endIndex; index++) {
        var record = globalConfig.meetingRecords.meetingRecords[index];
        // record = new MeetingRecord();
        CreateMeetomgRecprdRow(meetingRecordTable, record.rowId, record.fileUrl, record.meetingSubject, record.meetingDate, record.meetingHoster, record.meetingAttend, record.meetingLength, record.meetingFileSize, delta <= 15);
    }

    var menu = [{
        name: '播放',
        // img: 'images/create.png',
        title: '播放',
        disable: 'false',
        fun: function (e) {
            e.currentTarget.parentNode.style.display = "none";
            MeetingRecordPlayRow();
        }
    }, {
        name: '下载',
        // img: 'images/update.png',
        title: '下载',
        disable: 'false',
        fun: function (e) {
            e.currentTarget.parentNode.style.display = "none";
            MeetingRecordDownLoadRow();
        }

    },
    {
        name: '编辑',
        // img: 'images/update.png',
        title: '编辑',
        disable: 'false',
        fun: function (e) {
            e.currentTarget.parentNode.style.display = "none";
            // alert('你点击了编辑');
            MeetingRecordEditRow();
        }
    },
    {
        name: '删除',
        // img: 'images/update.png',
        title: '删除',
        disable: 'false',
        fun: function (e) {
            e.currentTarget.parentNode.style.display = "none"
            MeetingRecordDeleteRow();
        }
    }
    ];

    //Calling context menu
    // MeetingDateTD, MeetingSubjectTD
    $('.MeetingSubjectTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });
    $('.MeetingDateTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });

    // MeetingHostTD, MeetingAttendTD,MeetingLengthTD,MeetingFileSizeTD
    $('.MeetingHostTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });
    $('.MeetingAttendTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });
    $('.MeetingLengthTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });
    $('.MeetingFileSizeTD').contextMenu(menu, { onOpen: OnMeunOpenForMeetingRecord });
   
    var trNodes = document.querySelectorAll(".MeetingRecordRow");
    for (var i = 0; i < trNodes.length; i++) {
        var trNode = trNodes[i];
        trNode.onclick = function () {
            clickMeetingRecordRow(this);
        }
    }

    var meetingRecordPageScope = document.getElementById("MeetingRecordPageScope");    
    if (globalConfig.meetingRecords.startIndex == 0 && globalConfig.meetingRecords.endIndex < 0) {
        meetingRecordPageScope.innerText = "0-0";
    }
    else {
        meetingRecordPageScope.innerText = (globalConfig.meetingRecords.startIndex + 1) + "-" + (globalConfig.meetingRecords.endIndex + 1);
    }
}

function onFailureForQueryMeetingRecords(sender, args) {
    alert('查询会议记录错误：' + args.get_message());
}

function CreateMeetomgRecprdRow(meetingRecordTable, rowId, fileUrl, meetingSubject, meetingDate, meetingHoster, meetingAttend, meetingLength, meetingFileSize, addBlankCell) {
    var row = meetingRecordTable.insertRow(0);
    row.rowId = rowId;
    row.fileUrl = fileUrl;
    row.className = "MeetingRecordRow";

    var meetingSubjectTD = row.insertCell(0);
    // var meetingMenuTD = row.insertCell(1);
    var meetingDateTD = row.insertCell(1);
    var meetingHostTD = row.insertCell(2);
    var meetingAttendTD = row.insertCell(3);
    var meetingLengthTD = row.insertCell(4);
    var meetingFileSizeTD = row.insertCell(5);

    /*if (addBlankCell) {
        var blankCell = row.insertCell(7);
        blankCell.style.width = "10px";
    }*/

    meetingSubjectTD.className = "MeetingSubjectTD";
    meetingSubjectTD.innerHTML = meetingSubject;
    var subjectLength = fucCheckLength(meetingSubject);
    if (subjectLength > 24) {
        meetingSubjectTD.title = meetingSubject;
        meetingSubjectTD.innerHTML = AddEllipsis(meetingSubject, 24); 
    }
   

//    meetingMenuTD.className = "MeetingMenuTD";
//    var meetingMenuSpan = document.createElement("Div");
//    meetingMenuSpan.className = "MeetingMenuSpan";
//    meetingMenuSpan.innerHTML = "...";
//    meetingMenuSpan.title = "打开菜单";
//    meetingMenuTD.appendChild(meetingMenuSpan);

    meetingDateTD.className = "MeetingDateTD";
    meetingDateTD.innerHTML = meetingDate;

    meetingHostTD.className = "MeetingHostTD";
    meetingHostTD.innerHTML = meetingHoster;
    var hostLength = fucCheckLength(meetingHoster);
    if (hostLength > 11) {
        meetingHostTD.Title = meetingHoster;
        meetingHostTD.innerHTML = AddEllipsis(meetingHoster, 11); 
    }

    meetingAttendTD.className = "MeetingAttendTD";
    var attendLength = fucCheckLength(meetingAttend);
    meetingAttendTD.innerHTML = meetingAttend;  
    if (attendLength > 21) {
        meetingAttendTD.title = meetingAttend;
        meetingAttendTD.innerHTML = AddEllipsis(meetingAttend, 21); 
    }   

    meetingLengthTD.className = "MeetingLengthTD";
    meetingLengthTD.innerHTML = meetingLength;

    meetingFileSizeTD.className = "MeetingFileSizeTD";
    meetingFileSizeTD.innerHTML = meetingFileSize;
}

function ClearRowInTable(tableId) {
    $("#" + tableId).find("tr").remove();
}

function RemoveRow(tableId, rowId) {
    $("#" + tableId).find("tr[rowId='" + rowId + "']").remove();
}

function MeetingRecordEditRow() {
    var currentRow =getCurrentSelectedRow();
    var url = globalConfig.editRecordUrl.replace("ID=RowId", "ID=" + currentRow.rowId);
    openDialogForMeetingRecord(url, "修改会议记录");
}

function MeetingRecordPlayRow() {
    var currentRow = getCurrentSelectedRow();
    var title = '正在播放'+ currentRow.fileUrl;
    $("#MeetingRecordMediaHoster").dialog({
        title: title,
        autoOpen: false,
        height: 450,
        width: 550,
        modal: true,
        buttons: {
        },
        close: function () {
            StopMeetingRecordPlay();
        }
    });
    $("#MeetingRecordMediaHoster").dialog("open");
    setTimeout(function () {        
        PlayerMediaBySliverlight(globalConfig.meetRecordFolder + currentRow.fileUrl);
    }, 1000);
}

var removedItem;
function MeetingRecordDeleteRow() {
    var currentRow = getCurrentSelectedRow();
  　var result = window.confirm("确认要删除该记录吗？(不能恢复)");
    if (result == true) {
        var clientContext = new SP.ClientContext();
        var web = clientContext.get_web();
        var recordList = web.get_lists().getByTitle(globalConfig.recordListName);
        removedItem = recordList.getItemById(currentRow.rowId);
        removedItem.deleteObject();
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onDeleteRecordSuccessed), Function.createDelegate(this, this.onDeleteRecordFailed));
    }
}

function onDeleteRecordSuccessed() {
    RefreshMeetingRecordsData(); // defined in MeetingRecords.js
}

function onDeleteRecordFailed(sender, args) {
    alert('删除记录失败:' + args.message);
}

function MeetingRecordDownLoadRow() {
    var currentRow = getCurrentSelectedRow();
    window.open(globalConfig.meetRecordFolder + currentRow.fileUrl);
}

function MeetingRecorNextPage() {
    if (globalConfig.meetingRecords && globalConfig.meetingRecords.canMoveNextPage()) {
        globalConfig.meetingRecords.moveNextPage();
        RenderMeetingRecords();
    }
    else {
        alert("没有下一页了!");
    }
}

function MeetingRecordPreviousPage() {
    if (globalConfig.meetingRecords && globalConfig.meetingRecords.canMovePreviousPage()) {
        // globalConfig.meetingRecords.canMovePreviousPage();
        globalConfig.meetingRecords.movePreviousPage();
        RenderMeetingRecords();
    }
    else {
        alert("没有上一页了!");
    }
}

function MeetingRecord(rowId, fileUrl, meetingSubject, meetingDate, meetingHoster, meetingAttend, meetingLength, meetingFileSize) {
    this.rowId = rowId;
    this.fileUrl = fileUrl;
    this.meetingSubject = meetingSubject;
    this.meetingDate = meetingDate;
    this.meetingHoster = meetingHoster;
    this.meetingAttend = meetingAttend;
    this.meetingLength = meetingLength;
    this.meetingFileSize = meetingFileSize;
}

function MeetingRecords() {
    this.totalRecords = 0;
    this.meetingRecords = new Array();
    this.recordPageSzie = 30;
    this.currentPage = 1;
    this.searchText = null;
    this.startIndex = 0;
    this.endIndex = 0;

    this.canMoveNextPage = function () {
        var modValue = this.totalRecords % this.recordPageSzie > 0 ? 1 : 0;
        var totalPages = Math.floor(this.totalRecords / this.recordPageSzie) + modValue;

        return this.currentPage < totalPages;
    }

    this.canMovePreviousPage = function () {
        return this.currentPage > 1;
    }

    this.moveNextPage = function () {
        if (this.canMoveNextPage()) {
            this.startIndex = this.recordPageSzie * this.currentPage;
            this.currentPage++;
            if (this.canMoveNextPage()) {
                this.endIndex = this.recordPageSzie * this.currentPage - 1;
            }
            else {
                this.endIndex = this.totalRecords -1;
            }
        }
    }

    this.movePreviousPage = function () {
        if (this.canMovePreviousPage()) {
            this.currentPage--;
            this.endIndex = this.recordPageSzie * this.currentPage -1;          
            this.startIndex = this.recordPageSzie * (this.currentPage -1);
        }
    }
}

// RefreshMeetingRecordsData


// code Meida player for
var mdeiaPlayerHostId;
var closeButton;
function getMediaPlayer() {
    if (mdeiaPlayerHostId) {
        var p = document.getElementById(mdeiaPlayerHostId)
        var obj = p.getElementsByTagName("object");
        return obj[0].Content.MediaPlayer;
    }
    else {
        var paramNodes = document.getElementsByTagName("param");
        for (i = 0; i < paramNodes.length; i++) {
            if (paramNodes[i].value && paramNodes[i].value == "/_layouts/clientbin/mediaplayer.xap") {
                mdeiaPlayerHostId = paramNodes[i].parentNode.parentNode.id;
                return paramNodes[i].parentNode.Content.MediaPlayer;
            }
        }
    }
}

function CloseMediaPlayer() {
    var playerDiv = document.getElementById(mdeiaPlayerHostId);
    playerDiv.style.display = "none";
    var closeMediaButtonDiv = document.getElementById("CloseMediaButtonDiv");
    closeMediaButtonDiv.style.display = "none";
}

function OpenMediaPlayer() {
    var playerDiv = document.getElementById(mdeiaPlayerHostId);
    // playerDiv.style.display = "";
    // var closeMediaButtonDiv = document.getElementById("CloseMediaButtonDiv");
   // closeMediaButtonDiv.style.display = "";
}

function GetTitle(source) {
    title = source;
    var index = title.lastIndexOf("/");
    title = title.substring(index + 1, title.length);
    return title
}

function PlayerMediaBySliverlight(source) {
    var playerObject = getMediaPlayer();
    playerObject.AutoPlay = true;
    playerObject.MediaSource = source;
    playerObject.MediaTitle = GetTitle(source);
    // OpenMediaPlayer();
   // setTimeout(playerObject.Play(), 1000);    
}

function OnMeunOpenForMeetingRecord(data, e) {
    if (e.currentTarget && e.currentTarget.parentNode) {
        var rowNode = e.currentTarget.parentNode;
        if (rowNode.tagName == 'TR') {
            clickMeetingRecordRow(rowNode);
        }
        }

    if (e.currentTarget.tagName == 'TR') {
        clickMeetingRecordRow(e.currentTarget);
    }

    var menus = document.querySelectorAll(data.menu.selector + " li");
    for (var index = 0; index < menus.length; index++) {
        if (menus[index].classList.contains("hidden")) {
            menus[index].classList.remove("hidden");
        }
    }
   
        if (globalConfig.isAdmin) {
            // do nothing
        }
        else {  // hide edit and delete menu
            var hiddenMenu = document.querySelector(data.menu.selector + " li[title='编辑']");
            hiddenMenu.setAttribute("class", "hidden");

            hiddenMenu = document.querySelector(data.menu.selector + " li[title='删除']");
            hiddenMenu.setAttribute("class", "hidden");
            data.deltaHeight = 24.4 * 2;
        }
    }

    function StopMeetingRecordPlay() {
        var player = getMediaPlayer();
        player.Stop();
        player.AutoPlay = false;
        player.MediaSource = null;
        player.MediaTitle = "";
    }